package com.spring.security.study.security_test.handler;


import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录失败处理类
 *
 * @Author: 王文龙
 * @Date: 2020/7/610:31
 * @Version: 1.0
 * @Describe: 描述:
 */
@Slf4j
@Component
public class UserLoginFailureHandler implements AuthenticationFailureHandler {


    /**
     * 当身份验证尝试失败时调用
     *
     * @param request   进行身份验证尝试的请求
     * @param response  响应
     * @param exception 为拒绝身份验证而引发的异常
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        //这些对于操作的处理类可以根据不同异常进行不同处理
        if (exception instanceof UsernameNotFoundException) {
            log.info("【登录失败】" + exception.getMessage());
            Map<String, Object> map = new HashMap<>();
            map.put("code", 500);
            map.put("msg", "用户名不存在");
            log.info("数据:{}",map);
            return;
        }
        if (exception instanceof LockedException) {
            log.info("【登陆失败】" + exception.getMessage());
            Map<String, Object> map = new HashMap<>();
            map.put("code", 500);
            map.put("msg", "用户被冻结");
            log.info("数据:{}",map);
            return;
        }
        if (exception instanceof BadCredentialsException) {
            log.info("【登陆失败】" + exception.getMessage());
            Map<String, Object> map = new HashMap<>();
            map.put("code", 500);
            map.put("msg", "用户名密码不正确");
            log.info("数据:{}",map);
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "登录失败");
        log.info("数据:{}",map);

    }
}
